package com.shanks.home.module.multythread;

import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.shanks.home.R;
import com.shanks.home.framework.CoreContext;

public class MultyThreadActivity extends Activity {

	private Button handlerBtn, asynctaskBtn, threadPoolBtn1, threadPoolBtn2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		this.setContentView(R.layout.activity_multythread);
		initView();
	}

	private void initView() {
		handlerBtn = (Button)this.findViewById(R.id.multythread_handler_btn);
		asynctaskBtn = (Button)this.findViewById(R.id.multythread_asynctask_btn);
		threadPoolBtn1 = (Button)this.findViewById(R.id.multythread_threadpool_btn_1);
		threadPoolBtn2 = (Button)this.findViewById(R.id.multythread_threadpool_btn_2);

		handlerBtn.setOnClickListener(onClickListener);
		asynctaskBtn.setOnClickListener(onClickListener);
		threadPoolBtn1.setOnClickListener(onClickListener);
		threadPoolBtn2.setOnClickListener(onClickListener);
	}

	private OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			int id = v.getId();
			if (id == R.id.multythread_handler_btn) {
				startActivity(new Intent(MultyThreadActivity.this, ShanksHandlerActivity.class));
			} else if (id == R.id.multythread_asynctask_btn) {
				startActivity(new Intent(MultyThreadActivity.this, ShanksAsyncTaskActivity.class));
			} else if (id == R.id.multythread_threadpool_btn_1) {
				testThreadPool1();
			} else if (id == R.id.multythread_threadpool_btn_2) {
				testThreadPool2();
			}

		}
	};

	private void testThreadPool1() {
		CoreContext.executorService.execute(new Runnable() {

			@Override
			public void run() {
				int total = 0;
				for (int i=0; i<10000; i++) {
					total = total + i;
				}
			}
		});

		CoreContext.executorService.execute(new Runnable() {

			@Override
			public void run() {
				int num = 0;
				for (int j=0; j<10000; j++) {
					num = num + j;
				}
			}
		});
	}

	private void testThreadPool2() {
		CoreContext.scheduleExecutorService.schedule(new Runnable() {

			@Override
			public void run() {
				int num = 0;
				for (int j=0; j<10000; j++) {
					num = num + j;
				}
			}
		}, 1000, TimeUnit.MILLISECONDS);

		CoreContext.scheduleExecutorService.schedule(new Runnable() {

			@Override
			public void run() {
				int total = 0;
				for (int i=0; i<10000; i++) {
					total = total + i;
				}
			}
		}, 1000, TimeUnit.MILLISECONDS);
	}
}